package com.qijian.maindata.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qijian.common.annotation.Log;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.page.TableDataInfo;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.common.utils.uuid.IdUtils;
import com.qijian.maindata.domain.Factory;
import com.qijian.maindata.domain.query.FactoryQuery;
import com.qijian.maindata.domain.query.FactoryUserQuery;
import com.qijian.maindata.domain.query.ProcessQuery;
import com.qijian.maindata.domain.vo.FactoryVo;
import com.qijian.maindata.domain.vo.ProcessVo;
import com.qijian.maindata.service.IFactoryService;
import com.qijian.maindata.service.IFactoryUserService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 工厂Controller
 *
 * @author ruoyi
 * @date 2021-08-19
 */
@Api(tags = "生产管理：工厂")
@RestController
@RequiredArgsConstructor
@RequestMapping("/maindata/factory")
public class FactoryController extends BaseController {

    private final IFactoryService factoryService;
    private final IFactoryUserService factoryUserService;

    /**
     * 查询工厂列表
     */
    @PreAuthorize("@ss.hasPermi('business:factory:list')")
    @GetMapping("/list")
    public TableDataInfo list(FactoryQuery query, IPage<FactoryVo> page) {
        return getDataTable(factoryService.pageVo(Page.of(page.getCurrent(), page.getSize()), WhereEntityTool.invoke(query)));
    }

    @PreAuthorize("@ss.hasPermi('business:factory:list')")
    @GetMapping("/list/user")
    public TableDataInfo user(FactoryUserQuery query) {
        return getDataTable(factoryUserService.list(WhereEntityTool.invoke(query)));
    }

    /**
     * 树形结构
     */
    @PreAuthorize("@ss.hasPermi('business:factory:list')")
    @GetMapping("/tree")
    public TableDataInfo list(FactoryQuery query) {
        return getDataTable(factoryService.list(WhereEntityTool.invoke(query)));
    }

    /**
     * 导出工厂列表
     */
    @PreAuthorize("@ss.hasPermi('business:factory:export')")
    @Log(title = "工厂", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FactoryQuery query) {
        return new ExcelUtil<>(FactoryVo.class).exportExcel(factoryService.listVo(WhereEntityTool.invoke(query)), "工厂数据");
    }

    /**
     * 获取工厂详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:factory:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(factoryService.getVoById(id));
    }

    /**
     * 新增工厂
     */
    @PreAuthorize("@ss.hasPermi('business:factory:add')")
    @Log(title = "工厂", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Factory factory) {
        //提前得到id，手动插入id
        Long id = IdUtils.singletonSnowId();
        factory.setId(id);
        factory.setTopId(id);
        buildAncestors(factory);
        factoryService.save(factory);
        factory.getUsers().forEach(action -> action.setFactoryId(factory.getId()));
        if(CollUtil.isNotEmpty(factory.getUsers())){
            return toAjax(factoryUserService.saveBatch(factory.getUsers()));
        }
        return AjaxResult.success();
    }

    /**
     * 修改工厂
     */
    @PreAuthorize("@ss.hasPermi('business:factory:edit')")
    @Log(title = "工厂", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Factory factory) {
        buildAncestors(factory);

        if (factory.getUsers() != null) {
            // 明细
            FactoryUserQuery factoryUserQuery = new FactoryUserQuery();
            factoryUserQuery.setFactoryId(factory.getId());
            factoryUserService.remove(WhereEntityTool.invoke(factoryUserQuery));

            factory.getUsers().forEach(action -> {
                action.setId(null);
                action.setFactoryId(factory.getId());
            });
            factoryUserService.saveBatch(factory.getUsers());
        }
        return toAjax(factoryService.updateById(factory));
    }

    private void buildAncestors(Factory factory) {
        if (factory.getParentId() != null) {
            //获取父级的祖级拼接父级id，得到祖级
            Factory f = factoryService.getById(factory.getParentId());
            if (f != null)
                factory.setAncestors((f.getAncestors() == null ? "" : f.getAncestors() + ",") + factory.getParentId());
            else
                factory.setParentId(null);
        }
        if (factory.getParentId() == null)
            factory.setAncestors(null);
    }

    /**
     * 删除工厂
     */
    @PreAuthorize("@ss.hasPermi('business:factory:remove')")
    @Log(title = "工厂", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(factoryService.removeByIds(ids));
    }


    /**
     * 工艺线路页面查看工序列表
     */
    @PreAuthorize("@ss.hasPermi('business:process:list')")
    @GetMapping("/process-list")
    public TableDataInfo list(ProcessQuery query, Page<ProcessVo> page) {
        return getDataTable(factoryService.processPageVo(Page.of(page.getCurrent(), page.getSize()), WhereEntityTool.invoke(query)));
    }


}
